package cn.edu.xmu.oomall.customer.dao;

import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.util.CloneFactory;
import cn.edu.xmu.oomall.customer.dao.bo.Address;
import cn.edu.xmu.oomall.customer.dao.bo.Customer;
import cn.edu.xmu.oomall.customer.mapper.jpa.AddressPoMapper;
import cn.edu.xmu.oomall.customer.mapper.po.AddressPo;
import cn.edu.xmu.oomall.customer.mapper.po.CustomerPo;
import jdk.dynalink.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author 谢传艳
 * @date 2024/12/18
 */
@Repository
@RequiredArgsConstructor
public class AddressDao {
    private final AddressPoMapper addressPoMapper;

    private void build(Address bo){
        bo.setAddressDao(this);
    }


    private Address build(AddressPo po){
        Address bo = CloneFactory.copy(new Address(), po);
        this.build(bo);
        return bo;
    }
    public Address insert(Address address) {
        AddressPo po = CloneFactory.copy(new AddressPo(), address);
        addressPoMapper.save(po);
        address.setId(po.getId());
        return address;
    }

    /**
     * 根据用户id查询地址数量
     * @param id 用户id
     * @return 地址数量
     */
    public Integer retrieveCountByCustomerId(Long id) {
        return addressPoMapper.countByCustomerId(id);
    }

    /**
     * 根据用户id查询地址
     * @param id 用户id
     * @return 地址列表
     */
    public List<Address> retrieveByCustomerId(Long id) {
        List<AddressPo> addressPoList = addressPoMapper.findAllByCustomerId(id);
        if(addressPoList.isEmpty()){
            return new ArrayList<>();
        }else {
            return addressPoList.stream().map(this::build).toList();
        }
    }

    /**
     * 根据id查询地址
     * @param id 地址id
     * @return 地址
     */
    public Address retrieveDefaultAddressByCustomerId(Long id) {
        Optional<AddressPo> defaultAddress = addressPoMapper.findByCustomerIdAndBeDefault(id, Address.DEFAULT);
        if(defaultAddress.isPresent()){
            return build(defaultAddress.get());
        }else {
            return null;
        }
    }

    /**
     * 更新地址
     * @param address 地址
     */
    public void save(Address address) {
        addressPoMapper.save(CloneFactory.copy(new AddressPo(), address));
    }

    /**
     * 根据id查询地址
     * @param id 地址id
     * @return 地址
     */
    public Address findById(Long id) {
        Optional<AddressPo> addressPo = addressPoMapper.findById(id);
        if(addressPo.isPresent()){
            return build(addressPo.get());
        }else{
            throw new BusinessException(ReturnNo.ADDRESS_NOTEXIST, String.format(ReturnNo.ADDRESS_NOTEXIST.getMessage(), id));
        }
    }

    /**
     * 根据id删除地址
     * @param id 地址id
     */
    public void deleteById(Long id) {
        addressPoMapper.deleteById(id);
    }
}
